import {Component, Inject, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {GnMessageService, GnTable} from "geminis-ng";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {GnTableColumn} from "geminis-ng/data/table.component";

@Component({
  selector: 'gn-manage-role-manage',
  templateUrl: './role-manage.component.html'
})
export class RoleManageComponent extends GnTable implements OnInit {

  columns: GnTableColumn[] = [
    {label: '角色', field: 'name'}
  ];

  private roleLoaded = false;

  constructor(private httpClient: HttpClient,
              private messageService: GnMessageService,
              private dialog: MatDialogRef<void>,
              @Inject(MAT_DIALOG_DATA) private roleId: string) {
    super();
  }

  confirm(): void {
    this.httpClient.put('/MANAGE-SERVICE/roles/' + this.roleId + '/manageRole', this.table.selectedIds)
      .subscribe(() => {
        this.messageService.success('角色关系已保存');
        this.dialog.close("confirmed");
      }, error => {
        this.messageService.error({message: '保存角色关系错误', error: error.error});
      });
  }

  ngOnInit(): void {
    this.table.loaded.subscribe(() => {
      if (this.roleLoaded) {
        return;
      }
      this.httpClient.get('/MANAGE-SERVICE/roles/' + this.roleId + '/manageRole')
        .subscribe((roles: any) => {
          this.table.selectIds(roles.map(role => role.id));
          this.roleLoaded = true;
        }, error => {
          this.messageService.error({message: '获取角色信息错误', error: error.error});
        });
    });
  }

}
